layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
      elem: '#startTime'
    });

    laydate.render({
      elem: '#endTime'
    });

    laydate.render({
      elem: '#startTime2'
        	,value:new Date()
    });

    laydate.render({
      elem: '#endTime2'
        	,value:new Date()
    });

    /**
     * 货运订单表管理
     */
    var OrderTransport = {
        tableId: "orderTransportTable"
    };

    /**
     * 初始化表格的列
     */
    OrderTransport.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {field: 'center',width: 80,align: 'center', toolbar: '#tableBar', title: 'Operations'},
            {field: 'customerOrder', sort: true, title: 'Customer Order No.',templet: '#customerOrderTpl', style:'font-weight: 600;',width:150},
            {field: 'tstate', sort: true, title: 'Status',templet: '#tstateTpl',
            	templet: function(d){
            		var str = "";
            		if (d.tstate == 'SHIPPED_OUT'){
                    	str += '<span style="color:#ffaa00;font-weight: bold;">SHIPPED_OUT</span>'
					} else if (d.tstate == 'COMPLETED'){
                      	str += '<span style="color:#19be6b;font-weight: bold;">COMPLETED</span>'
					} else if (d.tstate == 'VOID'){
                      	str += '<span style="color:#909399;font-weight: bold;">VOID</span>'
					} else if (d.tstate == 'PENDING_DISPATCH'){
                      	str += '<span style="color:#20a0ff;font-weight: bold;">PENDING_DISPATCH</span>'
					}
            		return str
            	}
			},
            {field: 'setMentiontime', sort: true, title: 'Shipment Date', style:'font-weight: 600;'},
            {field: 'undertime', sort: true, title: 'Order Time'},
            {field: 'createName', title: 'Creator'},
            {field: 'getUnit', title: 'Receiving Unit', style:'font-weight: 600;',width:180},
            {field: 'getLocation', title: 'Receiving Address' ,width:250},
            {field: 'nodes', title: 'Remarks' ,width:160, totalRowText: 'Total:'},
            {field: 'getPeople', title: 'Contact Person'},
            {field: 'getTel', title: 'Contact Number'},
            {field: 'kilometer', title: 'Distance (km)'},
            {field: 'goodsNum', title: 'Product Count', totalRow: true},
            {field: 'totalNum', title: 'Quantity', totalRow: true},
            {field: 'totalVolume', title: 'Volume', totalRow: true},
            
            {field: 'operateName', sort: true, title: 'Project'},
            {field: 'customerName', sort: true, title: 'Customer'},
            {field: 'transportNumber', sort: true, title: 'Transport Order No.',templet: '#transportNumberTpl', style:'font-weight: 600;'},
            

            {field: 'lineName', sort: true, title: 'Route'},

            {field: 'setUnit', sort: true, title: 'Loading Unit'},
            {field: 'setLocation', sort: true, title: 'Loading Address'},

            {field: 'createTime', sort: true, title: 'Creation Time'},
            {field: 'submitTime', sort: true, title: 'Submission Time'},
            {field: 'submitName', title: 'Submitter'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    OrderTransport.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['getUnit'] = $("#getUnit").val();
        queryData['tstate'] = $("#tstate").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['startTime2'] = $("#startTime2").val();
        queryData['endTime2'] = $("#endTime2").val();
        table.reload(OrderTransport.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + OrderTransport.tableId,
        url: Feng.ctxPath + '/orderTransport/query',
        page: true,
        limit: 60,
		limits:[40,60,120,240,360,480,1200],
        height: "full-60",
        cellMinWidth: 100,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        totalRow: true ,//开启合计行
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: OrderTransport.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        OrderTransport.search();
    });

    /**
     * 撤回
     */
    OrderTransport.revoke = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/orderTransport/revoke?id="+data.id, function (data) {
                if(data.success){
                	Feng.success("Revoke successfully!");
                	table.reload(OrderTransport.tableId);
                } else {
                    Feng.error("Revoke failed!" + data.message + "!");
                }
            }, function (data) {
                Feng.error("Revoke failed!" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Feng.confirm("Are you sure you want to REVOKE the selected order?", operation);
    };
    
    // 批量撤回
    $('#btnRevoke').click(function () {
    	var checkStatus = table.checkStatus('orderTransportTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
            	if(data[i].tstate != 'PENDING_DISPATCH'){
					layer.msg('Only PENDING_DISPATCH orders can be REVOKED');
					return
            	}
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransport/btnRevoke?ids="+ids, function (data) {
	                if(data.success){
	                	Feng.success("Revoke successfully!");
	                	table.reload(OrderTransport.tableId);
	                } else {
	                    Feng.error("Revoke failed!" + data.message + "!");
	                }
                }, function (data) {
                    Feng.error("Revoke failed!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Are you sure you want to Revoke the selected orders?", function () {
                Feng.success("Revoke successfully!");
                table.reload(OrderTransport.tableId);
            });
		} else {
			layer.alert('please select at least one data');
		}
    });
    
    // 批量删除
    $('#btnDelete').click(function () {
    	var checkStatus = table.checkStatus('orderTransportTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
            	if(data[i].tstate == 'VOID' || data[i].tstate == 'PENDING_DISPATCH'){
            	} else {
					layer.msg('Only PENDING_DISPATCH or VOID orders can be deleted');
					return
				}
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransport/btnDelete?ids="+ids, function (data) {
	                if(data.success){
	                	Feng.success("Deleted successfully!");
	                	table.reload(OrderTransport.tableId);
	                } else {
	                    Feng.error("Deletion failed!" + data.message + "!");
	                }
                }, function (data) {
                    Feng.error("Deletion failed!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Are you sure you want to delete the selected orders?", operation);
		} else {
			layer.alert('Please select at least one data record');
		}
    });


    /**
     * 导出excel按钮
     */
    OrderTransport.exportExcel = function () {
        var checkRows = table.checkStatus(OrderTransport.tableId);
        var originalColumns = OrderTransport.initColumn()[0];
        var dataToExport = checkRows.data;
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            // table.exportFile(tableResult.config.id, checkRows.data, 'xls');
            dataToExport = dataToExport.map(function (row) {
                delete row.id; // 移除不需要的字段
                delete row.center;
                return row;
            });
            // 创建新的 columns 数组，只包含需要导出的列
            var exportColumns = originalColumns.filter(column => {
                // 排除表头
                return column.field !== 'id' && column.field !== 'center';
            });

            // 导出数据
            layer.confirm('Please select export format:', {
                btn: ['xlsx', 'xls'],
            }, function (index) {
                tableToExcel(dataToExport, exportColumns, 'Transport Order Query.xlsx');
                layer.close(index);
            }, function (index) {
                table.exportFile(tableResult.config.id, checkRows.data, 'xls')
                layer.close(index);
            })
        }
    };


    $('#btnExp').click(function (){
        OrderTransport.exportExcel();
    })
    
    // 发起
    OrderTransport.launch = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/orderTransport/launch?id="+data.id, function (data) {
                if(data.success){
                	Feng.success("Launched successfully!");
                	table.reload(OrderTransport.tableId);
                } else {
                    Feng.error("Launch failed!" + data.message + "!");
                }
            }, function (data) {
                Feng.error("Launch failed!" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Feng.confirm("Are you sure you want to re-launch the selected transport order?", operation);
    };

    // 单击行事件
    table.on('row(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
    });

    // 工具条点击事件
    table.on('tool(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'detailedSign' || layEvent ==='huoyundetailedSign') {
            layer.open({
                type: 2,
                title: 'Product Details',
                area: ['1000px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDetailed?transportNumber=' + data.transportNumber,
            });
        } else if (layEvent === 'launch') {
        	OrderTransport.launch(data);
        } else if (layEvent === 'revoke') {
        	OrderTransport.revoke(data);
        }
    });

});






